import { createRouter, createWebHashHistory } from "vue-router"

const router = createRouter({
  history: createWebHashHistory(), // 页面采用hash
  routes: [
    {
      path: '/',
      redirect: '/login' // 重定向
    },
    {
      path: '/login',
      name: 'login',
      component: (() => import('./components/Login.vue'))
    },
    {
      path: '/home',
      name: 'home',
      component: (() => import('./components/Home.vue')),
      redirect: '/users',
      children: [
        {
          path: '/users',
          name: 'users',
          component: (() => import('./components/users/Users.vue')),
        },
        {
          path: '/rights',
          name: 'rights',
          component: (() => import('./components/powers/Rights.vue'))
        },
        {
          path: '/roles',
          name: 'roles',
          component: (() => import('./components/powers/Roles.vue'))
        },
        {
          path: '/categories',
          name: 'categories',
          component: (() => import('./components/goods/Categories.vue'))
        },
        {
          path: '/goods',
          name: 'goods',
          component: (() => import('./components/goods/Goods.vue'))
        },
        {
          path: '/goods/add',
          name: 'add',
          component: (() => import('./components/goods/Add.vue'))
        },
        {
          path: '/params',
          name: 'params',
          component: (() => import('./components/goods/Params.vue'))
        },
        {
          path: '/orders',
          name: 'orders',
          component: (() => import('./components/orders/Orders.vue'))
        },
        {
          path: '/reports',
          name: 'reports',
          component: (() => import('./components/reports/Reports.vue'))
        },
      ]
    },
  ]
});

// 挂载路由导航守卫
// 导航守卫 判断是否登录
router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页面，直接放行
  if (to.path === '/login') return next();

  // 从sessionStorage中获取保存的token值
  const tokenStr = window.sessionStorage.getItem('token');

  // 没有token值，强制跳转到登录页
  if (!tokenStr) return next('/login');

  next()
})

export default router;